package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author kaoM1Jy
 * @date 2025/10/9 17:29
 * @description:
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ClueMapper clueMapper;

    @Override
    public List<Activity> getByType(Integer type) {
        return activityMapper.getByType(type);
    }

    @Override
    public void update(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public Activity getByID(Integer id) {
        Activity activity = activityMapper.getByID(id);
        return activity;
    }

    @Override
    public void deleteByID(Integer id) {
        List<Clue> clues = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        if (!clues.isEmpty()) {
            log.error("当前活动{}被线索 引用，无法删除", id);
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }

        activityMapper.deleteByID(id);
    }

    @Override
    public void add(Activity activity) {
        log.info("添加活动：{}", activity);
        //参数校验
        boolean hasNullField = BeanUtil.hasNullField(activity, "discount", "voucher", "createTime", "updateTime", "id");
        if (hasNullField) {
            log.error("参数有误");
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }


    @Override
    public PageResult<Activity> page(Integer channel, Integer type, Integer status, Integer page, Integer pageSize) {
        Integer count = activityMapper.count(channel, type, status);
        Integer offset = (page - 1) * pageSize;
        List<Activity> result = activityMapper.select(channel, type, status, offset, pageSize);
        return PageResult.<Activity>builder()
                .total( count)
                .rows(result)
                .build();
    }
    }

